<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="年月" prop="month">
                    <el-date-picker v-model="listQuery.month" type="month" placeholder="请选择月份">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="所属医院" prop="hid">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" v-model="listQuery.hid" placeholder="请选择医院">
                        <el-option v-for="item in hospitalOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                    <el-button size="small" class="filter-item" type="danger" icon="el-icon" @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;">
            <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
        </div>
        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column width="80px" align="center" type="index" label="序号"></el-table-column>
            <el-table-column align="center" label="时间年/月" prop="date"></el-table-column>
            <el-table-column align="center" label="所属医院" prop="hospitalName"></el-table-column>
            <el-table-column align="center" label="衣物总量" prop="clothesCnt"></el-table-column>
            <el-table-column align="center" label="缝补总量" prop="mendCnt"></el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="text" icon="document" @click="handleDetailDownload(scope.row)" :loading="listLoading">下载报表</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[20,50,100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { parseTime } from '@/utils'
  import exportExcel from '@/components/Excel/exportExcel'
  import { fetchHospitalList } from '@/api/hospital'
  import { reportMonthTypeList, reportHospitalAllReport, reportHospitalReport } from '@/api/report'

  // 列表字段：时间年/月、医院、衣物总量、缝补总量、操作
  export default {
    name: 'ReportHospital',
    data() {
      return {
        tableKey: 0,
        list: [],
        total: null,
        listLoading: false,
        listQuery: {
          page: 1,
          size: 20,
          hid: '',
          month: parseTime(new Date(), '{y}-{m}')
        },
        hospitalOptions: [],
        downloadLoading: false
      }
    },
    components: {
      exportExcel
    },
    computed: {
      ...mapGetters([
        'fid'
      ])
    },
    created: function() {
      this.getHospital()
      this.getList()
    },
    filters: {
      parseTime
    },
    methods: {
      getHospital() {
        fetchHospitalList({ page: 1, size: 500 }).then(response => {
          this.hospitalOptions = response.data && response.data.list || []
        })
      },
      getList() {
        if (!this.listQuery.month) {
          this.$message({ message: '请先选择查询年月', type: 'error', showClose: true })
          return
        }
        this.listLoading = true
        var query = {
          page: this.listQuery.page,
          size: this.listQuery.size,
          hid: this.listQuery.hid,
          month: this.listQuery.month
        }
        reportMonthTypeList(query).then(response => {
          this.list = response.data && response.data.list || []
          this.total = Number.parseInt(response.data.count)
          // if (this.list.length) { this.list.splice(this.list.length - 1) }
          this.listLoading = false
        }).catch(e => {
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetFilter() {
        this.$refs['listQuery'].resetFields()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDetailDownload(row) {
        this.listLoading = true
        var query = {
          page: 1,
          size: 1000,
          hid: row.hid,
          month: row.date
        }
        reportHospitalReport(query).then(response => {
          var excelList = response.data || []
          if (!excelList || !excelList.length) {
            this.$message({ message: '没有可下载的报表', type: 'error', showClose: true })
            this.listLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            // 合计：衣物总量、洗涤总额、缝补总量、缝补总额、合计总金额
            excelList[excelList.length - 1].date = '合计'
            excelList[excelList.length - 1].hospitalName = ''
            excelList[excelList.length - 1].departmentName = ''
            excelList[excelList.length - 1].typeName = ''
            excelList[excelList.length - 1].categoryName = ''
            const tHeader = ['时间年/月/日', '所属医院', '科室', '品类', '分类', '衣物数量', '洗涤金额', '缝补数量', '缝补金额', '合计金额']
            const filterVal = ['date', 'hospitalName', 'departmentName', 'typeName', 'categoryName', 'clothesCnt', 'clothesMoney', 'mendCnt', 'mendMoney', 'allMoney']
            const data = this.formatJson(filterVal, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '医院明细表' + row.hospitalName + row.date,
              autoWidth: true
            })
            this.listLoading = false
          })
        }).catch(e => {
          this.listLoading = false
        })
      },
      handleDownload() {
        if (!this.listQuery.month) {
          this.$message({ message: '请先选择查询年月', type: 'error', showClose: true })
          return
        }
        this.downloadLoading = true
        var query = {
          page: 1,
          size: 1000,
          hid: this.listQuery.hid,
          month: this.listQuery.month
        }
        reportHospitalAllReport(query).then(response => {
          var excelList = response.data || []
          if (!excelList || !excelList.length) {
            this.$message({ message: '没有可下载的报表', type: 'error', showClose: true })
            this.downloadLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            excelList[excelList.length - 1].date = '合计'
            excelList[excelList.length - 1].hospitalName = ''
            const tHeader = ['年/月', '所属医院', '衣物总量', '洗涤总额', '缝补总量', '缝补总额', '合计总金额']
            const filterVal = ['date', 'hospitalName', 'clothesCnt', 'clothesMoney', 'mendCnt', 'mendMoney', 'allMoney']
            const data = this.formatJson(filterVal, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '医院总表' + query.month,
              autoWidth: true
            })
            this.downloadLoading = false
          })
        }).catch(e => {
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }))
      }
    }
  }
</script>

<style scoped>
    .el-range-editor.el-input__inner {
        width: 273px;
        padding: 3px;
    }
</style>